﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
using WorkflowEngine.Entitys;

namespace WorkflowEngine.Managers
{
    public interface IBillCodeManager
    {
        string New(string objName, string prefix, int num);
    }
    public class BillCodeManager : DomainService, IBillCodeManager
    {
        public IRepository<BillCode> billCodeRepository;

        public BillCodeManager(IRepository<BillCode> billCodeRepository)
        {
            this.billCodeRepository = billCodeRepository;
        }
        static List<BillCode> billCodes = new List<BillCode>();
        [UnitOfWork]
        public virtual string New(string objName, string prefix, int num)
        {

            lock (billCodes)
            {
                var entity = this.billCodeRepository.FirstOrDefaultAsync(m => m.ObjName == objName && m.Prefix == prefix).Result;
                string code = "";

                if (entity == null)
                {
                    code = $"{prefix}" + 1.ToString("D" + num);
                    entity = new BillCode { TenantId = CurrentTenant.Id, Prefix = prefix, ObjName = objName, MaxValue = 1 };
                    entity = this.billCodeRepository.InsertAsync(entity).Result;
                }
                else
                {
                    entity.MaxValue = entity.MaxValue + 1;
                    code = $"{prefix}" + entity.MaxValue.ToString("D" + num);
                    entity = this.billCodeRepository.UpdateAsync(entity).Result;
                }
                return code;
            }
        }
    }
}


